package com.fzy.common.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
//import org.apache.http.entity.mime.HttpMultipartMode;
//import org.apache.http.entity.mime.MultipartEntityBuilder;
//import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @author 冯赵杨
 * @Desc httpClient工具类
 * @date 2017年9月12日
 */
public class HttpClientUtil {
    private HttpClientUtil() {
    }

    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
    private static final String DEFAULT_CHARSET = "UTF-8";
    private static final String CONTENT_TYPE = "application/json";

    /**
     * post请求
     *
     * @param url  url地址
     * @param json 参数
     * @return
     */
    public static JSONObject post2Json(String url, String json) {
        //post请求返回结果
        JSONObject jsonResult = null;
        HttpPost method = new HttpPost(url);
        try {
            if (null != json) {
                //解决中文乱码问题
                StringEntity entity = new StringEntity(json, DEFAULT_CHARSET);
                entity.setContentEncoding(DEFAULT_CHARSET);
                entity.setContentType(CONTENT_TYPE);
                method.setEntity(entity);
            }
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpResponse response = httpClient.execute(method);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                return null;
            }

            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String str = EntityUtils.toString(entity);
                jsonResult = JSON.parseObject(str);
            }
        } catch (IOException e) {
            logger.error("post请求提交失败:" + url, e);
        }
        return jsonResult;
    }

    /**
     * 发送get请求
     *
     * @param url 路径
     * @return
     */
    public static JSONObject get2Json(String url) {
        //get请求返回结果
        JSONObject jsonResult = null;
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //发送get请求
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpClient.execute(httpGet);

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                return null;
            }

            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String strResult = EntityUtils.toString(entity);
                jsonResult = JSON.parseObject(strResult);
                url = URLDecoder.decode(url, DEFAULT_CHARSET);
            } else {
                logger.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            logger.error("get请求提交失败:" + url, e);
        }
        return jsonResult;
    }

    /**
     * 发送post请求
     *
     * @param url   请求URL
     * @param param 请求参数map
     * @return
     */
    public static String post(String url, Map<String, String> param) {
        return post(url, null, param);
    }

    /**
     * 发送post请求
     *
     * @param url     请求URL
     * @param param   请求参数map
     * @param headers 请求头map
     * @return
     */
    public static String post(String url, Map<String, String> headers, Map<String, String> param) {
        // 创建默认的httpClient实例.
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建httppost 发送post请求
        HttpPost httpPost = new HttpPost(url);

        // 创建header参数
        if (null != headers) {
            for (Entry<String, String> header : headers.entrySet()) {
                httpPost.addHeader(header.getKey(), String.valueOf(header.getValue()));
            }
        }

        // 创建参数列表 ,封装请求参数
        List<NameValuePair> formParams = new ArrayList<NameValuePair>();
        if (param != null) {
            Iterator<Entry<String, String>> iter = param.entrySet().iterator();
            while (iter.hasNext()) {
                Entry<String, String> entry = iter.next();
                BasicNameValuePair bvp = new BasicNameValuePair(entry.getKey(), entry.getValue());
                formParams.add(bvp);
            }
        }

        CloseableHttpResponse response = null;
        UrlEncodedFormEntity urlEncodedFormEntity = null;
        try {
            urlEncodedFormEntity = new UrlEncodedFormEntity(formParams, DEFAULT_CHARSET);
            httpPost.setEntity(urlEncodedFormEntity);
            response = httpClient.execute(httpPost);

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                return EntityUtils.toString(entity, DEFAULT_CHARSET);
            }
        } catch (Exception e) {
            logger.error("请求异常，错误信息为:{}", e.getMessage());

        } finally {
            closeResource(response, httpClient);// 关闭连接，释放资源

        }
        return null;
    }

    /**
     * json格式 post请求
     *
     * @param url
     * @param json
     * @return
     */
    public static String post(String url, String json) {
        return post(url, null, json);
    }

    /**
     * json格式 post请求
     *
     * @param url
     * @param json
     * @param headers 请求头map
     * @return
     */
    public static String post(String url, Map<String, String> headers, String json) {
        // 创建默认的httpClient实例.
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建httppost 发送post请求
        HttpPost httpPost = new HttpPost(url);
        if (null != headers) {
            for (Entry<String, String> param : headers.entrySet()) {
                httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
            }
        }
        httpPost.setEntity(new StringEntity(json, DEFAULT_CHARSET));
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                return EntityUtils.toString(entity, DEFAULT_CHARSET);
            }
        } catch (Exception e) {
            logger.error("请求异常，错误信息为:{}", e.getMessage());

        } finally {
            closeResource(response, httpClient);// 关闭连接，释放资源

        }

        return null;
    }

    /**
     * get请求
     *
     * @param url
     * @return
     */
    public static String get(String url) {
        return get(url, null);
    }

    /**
     * get请求
     *
     * @param url
     * @param headers 请求头map
     * @return
     */
    public static String get(String url, Map<String, String> headers) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        if (null != headers) {
            for (Entry<String, String> param : headers.entrySet()) {
                httpGet.addHeader(param.getKey(), String.valueOf(param.getValue()));
            }
        }

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String data = EntityUtils.toString(entity, DEFAULT_CHARSET);
                return data;
            }
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug("请求异常，错误信息为:{}", e.getMessage());
            }

        } finally {
            closeResource(response, httpClient);// 关闭连接，释放资源
        }
        return null;
    }

    private static final void closeResource(CloseableHttpResponse response, CloseableHttpClient httpClient) {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 上传文件
     *
     * @param url       上传请求URL
     * @param paramName 文件参数名
     * @param fileName  文件名
     * @param file      文件对象
     * @return
     * @author bang
     */
    public static String upload(String url, String paramName, String fileName, File file) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
//            FileBody fileBody = new FileBody(file);
//            HttpEntity httpEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532)
//                    .addPart(paramName, fileBody).build();
            HttpEntity httpEntity = null;
            httpPost.setEntity(httpEntity);
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String data = EntityUtils.toString(entity, DEFAULT_CHARSET);
                return data;
            }
        } catch (Exception e) {
            logger.error("请求异常，错误信息为:{}", e.getMessage());

        } finally {
            closeResource(response, httpClient);// 关闭连接，释放资源
        }

        return null;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
		/*File file = new File("C:\\Users\\bang\\Desktop\\DEMO7.rar");
		upload("file", "http://localhost:8080/ucenter/notice/upload.do", file.getName(), file);*/

        String rep = HttpClientUtil.get("https://www.baidu.com");
        System.out.println(rep);
    }
}
